package com.zs.toolbox.web2j.system.storage.service;

import com.zs.toolbox.web2j.common.exception.WtExceptions;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;

/**
 * Copyright ©2016
 *
 * @author shuai.zhang  on 2017/6/2
 * @version 1.0.0
 * @description
 */
@Service
@Slf4j
@ConditionalOnProperty(prefix = "wt.storage.local", name = "path")
public class WtLocalStorageServiceImpl implements WtStorageService {

	@Value("${wt.storage.local.path}")
	String localSavePathPrefix;

	public WtLocalStorageServiceImpl() {
	    log.info("启动本地存储器");
	}

	public String saveFile(String relativeFullFilePath, InputStream inputStream) {
		String absFullName = String.format("%s/%s", localSavePathPrefix,relativeFullFilePath);
		String path = FilenameUtils.getFullPathNoEndSeparator(absFullName);

		try {
			log.debug("创建文件存储文件夹:{}",path);
			FileUtils.forceMkdir(new File(path));
			FileUtils.copyToFile(inputStream, new File(absFullName));
			log.debug("上传文件成功:{}", absFullName);
			return relativeFullFilePath;
		} catch (IOException e) {
			log.error(String.format("upload file %s", absFullName), e);
			throw WtExceptions.E_STORAGE_LOCAL_UPLOAD;
		}
	}
}
